const app = getApp();
const { http_request } = require("../../utils/request");
const { insertPileInfo } = require("../../utils/api");

Page({
  data: {
    searching: false,
    devicesList: [],
    list_height: 0,
  },

  // 启动蓝牙扫描
  startBluetoothScan() {
    const that = this;

    wx.closeBluetoothAdapter({
      complete() {
        wx.openBluetoothAdapter({
          success() {
            wx.startBluetoothDevicesDiscovery({
              allowDuplicatesKey: false,
              success() {
                that.setData({ searching: true, devicesList: [] });
              },
            });
          },
          fail() {
            wx.showModal({
              title: '提示',
              content: '请检查手机蓝牙是否打开',
              showCancel: false,
              success() {
                that.setData({ searching: false });
              },
            });
          },
        });
      },
    });
  },

  // 停止蓝牙扫描
  stopBluetoothScan() {
    if (this.data.searching) {
      wx.stopBluetoothDevicesDiscovery({
        success: () => {
          console.log('停止蓝牙设备扫描');
          this.setData({ searching: false });
        },
        fail(err) {
          console.log('停止扫描失败:', err);
        }
      });
    }
  },

  // 连接到设备
  Connect(e) {
    console.log('点击的设备ID:', e.currentTarget.id);
    const deviceId = e.currentTarget.id;
    const device = this.data.devicesList.find(item => item.deviceId === deviceId);
    const { name } = device || {};

    if (!deviceId) {
      wx.showToast({ title: '设备ID为空', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '连接蓝牙设备中...' });

    this.stopBluetoothScan();

    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        console.log('连接成功:', res);
        wx.hideLoading();
        wx.showToast({ title: '连接成功', icon: 'success', duration: 1000 });

        wx.navigateTo({
          url: `../charging/charging?connectedDeviceId=${deviceId}`,
        });

        // ✅ 存储设备名称到 chargingPileId
        wx.setStorageSync("chargingPileId", name);
        console.info("蓝牙名称为：", name)
        console.info("设备ID为：", deviceId)
      },
      fail: (err) => {
        console.log('连接失败:', err);
        wx.hideLoading();
        wx.showModal({ title: '提示', content: '连接失败', showCancel: false });
      },
    });
  },

  // 页面加载时自动启动扫描
  onLoad() {
    const { windowHeight, windowWidth } = app.globalData.SystemInfo;
    const list_height = ((windowHeight - 50) * (750 / windowWidth)) - 60;
    this.setData({ list_height });

    this.startBluetoothScan();

    wx.onBluetoothAdapterStateChange(res => {
      this.setData({ searching: res.discovering && res.available });
    });

    wx.onBluetoothDeviceFound(devices => {
      const newDevice = this.normalizeDeviceData(devices);
      if (newDevice && !this.isDeviceExist(newDevice)) {
        this.setData({ devicesList: [...this.data.devicesList, newDevice] });
      }
    });
  },

  // 页面隐藏时停止扫描
  onHide() {
    this.setData({ devicesList: [] });
    if (this.data.searching) {
      this.stopBluetoothScan();
    }
  },

  // 规范化设备数据
  normalizeDeviceData(devices) {
    if (devices.deviceId) {
      const advertisData = devices.advertisData ? app.buf2hex(devices.advertisData) : '';
      return { ...devices, advertisData };
    } else if (devices.devices?.[0]) {
      const advertisData = devices.devices[0].advertisData ? app.buf2hex(devices.devices[0].advertisData) : '';
      return { ...devices.devices[0], advertisData };
    } else if (devices[0]) {
      const advertisData = devices[0].advertisData ? app.buf2hex(devices[0].advertisData) : '';
      return { ...devices[0], advertisData };
    }
    return null;
  },

  // 检查设备是否已存在
  isDeviceExist(device) {
    return this.data.devicesList.some(item => item.deviceId === device.deviceId);
  },
});
